package com.lzy.sso.cas.service;

import com.lzy.sso.cas.authenticator.Authenticator;
import com.lzy.sso.cas.generator.TokenGenerator;
import com.lzy.sso.cas.pojo.Identification;
import com.lzy.sso.cas.pojo.Subject;
import com.lzy.sso.cas.principle.Principle;
import com.lzy.sso.cas.store.TokenManagement;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: lzy
 * @Date: 2022/4/30 20:38
 * @Description:
 */
public abstract class AbstractAuthenticationService implements AuthenticationService {
    @Autowired
    protected Authenticator authenticator; // 认证器

    @Autowired
    protected TokenGenerator generator; // token生成器

    @Autowired
    protected TokenManagement tokenManagement; // token管理器

    /**
     * 简单模拟登录
     * @param subject
     * @return
     */
    public Principle login(Subject subject) {
        return authenticator.login(subject);
    }

    /**
     * 认证token的有效性
     * 1.存不存在
     * 2.有无过期
     * @param token
     * @return
     */
    public boolean auth(String token) {
        return tokenManagement.exists(token);
    }

    /**
     * 随机获取一个token 提供模板方法
     * @return
     */
    @Override
    public String processToken(HttpServletRequest request, HttpServletResponse response,Principle principle) {
        String token=generator.generate();
        Identification identification=new Identification();
        identification.setPrinciple(principle);

        doProcess(request,response,token,identification);
        tokenManagement.addToken(token,identification);

        Cookie cookie=new Cookie("token",token);
        //cookie.setSecure(true);
        cookie.setHttpOnly(true);
        cookie.setMaxAge(60*60);

        response.addCookie(cookie);
        return token;
    }

    /**
     * 子类实现自定义
     * @param request
     * @param response
     * @param token
     */
    protected abstract void doProcess(HttpServletRequest request,HttpServletResponse response,String token,Identification identification);
}
